﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Xml.Serialization;
using TestCommonWindow.Helpers;
using TestCommonWindow.Model;

namespace TestCommonWindow.Common
{
    public class BusinessProcess
    {
        /// <summary>
        /// 序列化XML文件
        /// </summary>
        /// <param name="path">the path to save the xml file</param>
        /// <param name="obj">the object you want to serialize</param>
        public static void SerializeToXml<T>(string path, T obj) where T : class
        {
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            string content = string.Empty;
            //serialize
            using (StringWriter writer = new StringWriter())
            {
                serializer.Serialize(writer, obj);
                content = writer.ToString();
            }
            //save to file
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.Write(content);
                }
            }
        }

        /// <summary>
        /// 反序列XML文件
        /// </summary>
        /// <param name="path">the path of the xml file</param>
        /// <param name="object_type">the object type you want to deserialize</param>
        public static T DeserializeFromXml<T>(string path) where T : class
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (StreamReader reader = new StreamReader(path))
            {
                return serializer.Deserialize(reader) as T;
            }
        }
        //判断文件是否已使用
        public static bool IsFileInUse(string path)
        {
            bool inUse = true;
            if (File.Exists(path))
            {
                FileStream fs = null;
                try
                {
                    fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
                    inUse = false;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message.ToString());
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }
                return inUse;           //true表示正在使用,false没有使用
            }
            else
            {
                return false;           //文件不存在则一定没有被使用
            }
        }
        public static bool SaveReport(TestResult entity)
        {
            string oneLineData = string.Empty;
            try
            {
                var reportDirInfo = new DirectoryInfo(GlobalInfo.reprotSaveDirectory);
                if (!reportDirInfo.Exists)
                {
                    reportDirInfo.Create();
                }
                //..\TestReport\Summary_20230816.csv
                string reportPath = Path.Combine(GlobalInfo.reprotSaveDirectory, string.Format("Summary_{0}.csv", DateTime.Now.ToString("yyyyMMdd")));
                //
                var reportFileInfo = new FileInfo(reportPath);
                if (!reportFileInfo.Exists)
                {
                    reportFileInfo.Create().Close();
                    using (FileStream fs=new FileStream(reportPath,FileMode.Open,FileAccess.Write,FileShare.ReadWrite))
                    {
                        using (StreamWriter sw=new StreamWriter(fs))
                        {
                            sw.BaseStream.Seek(0, SeekOrigin.End);
                            sw.WriteLine(string.Format("QRCode,AppVersion,Result,TestItem,Computer,TotalTime,TestTime"));
                            sw.WriteLine(string.Format("{0},{1},{2},{3},{4},{5},{6}",entity.QRCode,entity.AppVersion, entity.Result,entity.TestItem,entity.Computer,entity.TotalTime,entity.TestTime));
                        }
                    }
                }
                else
                {
                    using (FileStream fs=new FileStream(reportPath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
                    {
                        using (StreamWriter sw=new StreamWriter(fs))
                        {
                            sw.BaseStream.Seek(0, SeekOrigin.End);
                            sw.WriteLine(string.Format("{0},{1},{2},{3},{4},{5},{6}", entity.QRCode,entity.AppVersion, entity.Result, entity.TestItem, entity.Computer, entity.TotalTime, entity.TestTime));
                        }
                    }

                }
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);//record log
                MessageBox.Show(ex.Message,"软件温馨提示!",MessageBoxButton.OK,MessageBoxImage.Error);
            }
            return false;
        }
    }
}
